import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
// import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { message,Modal } from 'ant-design-vue';
import { isEmpty } from '@/utils/util'
import { toRaw } from 'vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const ACCESS_TOKEN = 'Access-Token'
// 登录页
const loginRoutePath = '/passport/login'
// 白名单
const whiteList = [loginRoutePath,'/index'] // no redirect whitelist
// 默认路由地址
const defaultRoutePath = '/'

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  // to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(to.meta.title))
  document.title = to.meta.title ? to.meta.title : '考级系统';
  // 超管后台自动登录
  const { query } = to
  // if (to.path === loginRoutePath && query['superLogin']) {
  //   store.dispatch('SuperLogin', {
  //     userId: query['userId'],
  //     token: query['token']
  //   })
  // }
  // console.log('status',toRaw(store.getters.userInfo));
  // if (to.path === '/sign') {
    // store.dispatch('GetInfo', {
    //   token: query['token']
    // }).then(result=>{
    //   let user = result.data.userInfo;
    //   if(user.avatar_id>0){
    //     //绑定资料
    //     console.log(user.avatar_id>0)
    //     // message.info('This is a normal message')
    //     next('/profile')
    //   }

    // }).catch(error=>{
    //   console.log(error)
    // })
    // next('/profile')
  // }

  /* has token */
  if (storage.get(ACCESS_TOKEN)) {
    // 已登录情况下访问登录页 - 跳转到默认页
    
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      if (to.path === '/sign') {
        store.dispatch('GetInfo', {}).then(result=>{
          let user = result.data.userInfo;
          if(user.avatar_id==0){
            message.info('请完善个人资料！')
            next('/profile');
          }else if(!user.grade_code){
            Modal.confirm({
              title: '温馨提示',
              content: '您还未绑定考级卡，现在去申请？',
              okText:'确定',
              cancelText:'取消',
              onOk() {next({ path: '/code' })},
              onCancel() {},
            });
          }else{
            next()
          }
         
        }).catch(()=>{
          store.dispatch('Logout')
          next(loginRoutePath)
        })
      }else{
        next()
      }
      
    }
  } else {
    // if (whiteList.includes(to.path)) {// 在免登录白名单，直接进入
    if (to.meta.requiresAuth!=true) {
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
